<template>
  <div class="h-all flex fd-c">
    <div class="fs-20 flex nodarg w-all ra-10 pr10 mr10 ai-c">
      <Select placeholder="年级" @change="initData(1)" clear class="w-100 b-0 hand fs-15 h-35" :data="nianji" props="t,v" v-model:label="query.gradeText" v-model="query.grade"></Select>
      <!-- <Select placeholder="单元" @change="initData(1)" clear class="w-120 b-0 hand fs-15 ml10 h-35" :data="unitList" props="t,v" v-model="query.unit"></Select> -->
      <!-- <Select placeholder="上下册" @change="initData(1)" clear class="w-90 b-0 hand fs-15 ml10 h-35" :data="[{value:1,label:'上册'},{value:2,label:'下册'}]" v-model="query.volume"></Select> -->
      <span class="flex-1"></span>
      <page @change="initData" :size="query.size" :total="query.total" :page="query.page"></page>
    </div>
    <div class="w-all mt10 flex-1 nodarg">
      <scroll>
        <div class="w-all pt10 pb10 pr15 flex fw ">
          <div @click="deepseek(item)" v-for="item in info.list" style="width:350px;height: 300px;" class="flex nodarg hand pt10 fd-c mb10 ml10 pl20 ra-10 glass-card">
            <div class="fs-40 fc-FF4500 fb">{{item.word}}</div>
            <div class="flex mt10 ai-c">
              <div @click.stop="onWordPlay(item.word,0)" class="fs-23 hand nodarg flex ai-c fc-aa">英：{{item.en_pronunciation}} <span class="iconfont icon-ting fs-25 fc-pri"></span></div>
              <div @click.stop="onWordPlay(item.word,1)" class="fs-23 ml30 hand nodarg flex ai-c fc-aa">美：{{item.us_pronunciation}} <span class="iconfont icon-ting fs-25 fc-pri"></span></div>
            </div>
            <div class="fs-16 mt10 pr10" v-html="item.exp"></div>
            <div class="flex fs-16 fd-c">
              <span class="mt10 fc-999" v-for="v in item.remark.demo.slice(0,3)"><span class="hand fc-aa nodarg" @click.stop="st.toSpeek(v.title)">{{v.title}}</span>：{{v.desc}}</span>
            </div>

          </div>
        </div>
      </scroll>
    </div>
  </div>

  <div v-if="info.curr" class="fixed flex ai-c sha-card jc-c at0 al0 ab0 ar0 ba-f2">

    <div style="width:85%;background-color:#14261ee3; padding: 18px 10px 18px 18px;" class="pp30 rel ra-10">
      <span @click.stop="info.curr=null" class="iconfont hand nodarg icon-bg-close fc-danger fs-50 abs at-45 ar-45"></span>
      <div class="flex pl20 w-all pt10 fd-c mb10 nodarg custom-scrollbar h-600 auto  rel">
        <div class="fs-40 flex ai-c fb">
          <span class="fc-fff">{{info.curr.word}}</span>
          <div @click.stop="onWordPlay(info.curr.word,0)" class="fs-23 hand ml30 nodarg flex ai-c fc-aa">英：{{info.curr.en_pronunciation}} <span class="iconfont icon-ting fs-25 fc-pri"></span></div>
          <div @click.stop="onWordPlay(info.curr.word,1)" class="fs-23 ml30 hand nodarg flex ai-c fc-aa">美：{{info.curr.us_pronunciation}} <span class="iconfont icon-ting fs-25 fc-pri"></span></div>
          <div class="fs-16 ml20 fc-fff pr10" v-html="info.curr.exp"></div>
        </div>

        <div class="flex fs-22 fd-c">
          <span class="mt10 pl20" v-for="v in info.curr.remark.demo"><span class="hand fc-fff nodarg" @click.stop="st.toSpeek(v.title)">{{advancedAutoCapitalize(v.title)}}</span><span style="color:#00f7a5;" class=" fs-19">：{{v.desc}}</span></span>
        </div>
        <div style="border-top:1px solid #fff" class="flex mt20 pt10 pb20 fs-22 fd-c mr10">
          <span class="mt10 pl20" v-for="v in info.curr.remark.j"><span class="hand fc-fff nodarg" @click.stop="st.toSpeek(v.title)">{{advancedAutoCapitalize(v.title)}}</span><span style="color:#00f7a5;" class=" fs-19">：{{v.desc}}</span></span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { nextTick, reactive, ref } from 'vue';
import yy from '@lib/mixin';
import useStore from '../../store';
import phrase from '../../assets/group';
const st = useStore();

const info = reactive({
  index: 0,
  phrase: null,
  list: [],
  curr: null
})

const nianji = [
  { t: '小学', v: 1 },
  { t: '初中', v: 2 },
  { t: '高中', v: 3 },
  { t: '大学', v: 4 },
]
const unitList = [
  { t: '一单元', v: 1 },
  { t: '二单元', v: 2 },
  { t: '三单元', v: 3 },
  { t: '四单元', v: 4 },
  { t: '五单元', v: 5 },
  { t: '六单元', v: 6 },
  { t: '七单元', v: 7 },
  { t: '八单元', v: 8 },
  { t: '九单元', v: 9 },
  { t: '十单元', v: 10 },
  { t: '十一单元', v: 11 },
  { t: '十二单元', v: 12 },
  { t: '十三单元', v: 13 },
  { t: '十四单元', v: 14 },
]

const query = reactive({
  grade: 1,
  gradeText: "小学",
  unit: "",
  volume: "",
  page: 1,
  size: 10,
  serch: '',
  total: 100
})

function deepseek(item) {
  info.curr = item;
  // yy.spinner.show()
  // console.log(`${item.word} 解说 中英对照 JSON输出`);
  
  // st.invoke('deepseek', { msg: `${item.word} 单词解说 中英对照 JSON输出` }).then(res => {
  //   yy.spinner.close()
  //   console.log(res);
    
  // })
}

function onWordPlay(word, type) {
  let src = `http://dict.youdao.com/dictvoice?type=${type}&audio=${word}`;
  if (info.playAudio) {
    info.playAudio.pause();
    info.playAudio = null;
  }

  info.playAudio = new Audio(src);
  info.playAudio.volume = 1;
  info.playAudio.play()
}

function advancedAutoCapitalize(str, capitalizeFirst = false) {
  if (!str) return str;

  // 转换为小写，然后处理特定情况
  let result = str.toLowerCase();

  // 处理"I"
  result = result.replace(/\bi\b/g, 'I');

  // 处理句子开头和标点符号后的字母
  const regex = /(^|[.!?]\s+)([a-z])/g;
  result = result.replace(regex, (match, p1, p2) => {
    return p1 + p2.toUpperCase();
  });

  // 处理特定专有名词（可扩展此列表）
  const properNouns = ['mr', 'mrs', 'dr', 'usa', 'uk'];
  properNouns.forEach(noun => {
    const regex = new RegExp(`\\b${noun}\\b`, 'g');
    result = result.replace(regex, noun.toUpperCase());
  });

  // 如果不需要首字母大写，且原句首字母是小写
  if (!capitalizeFirst && str[0] === str[0].toLowerCase()) {
    result = result.charAt(0).toLowerCase() + result.slice(1);
  }

  return result;
}

function initData(page) {
  if (page) query.page = page;
  let where = `${query.grade && (` and grade=${query.grade}`) || ''}
  ${query.unit && (` and unit=${query.unit}`) || ''}
  ${query.volume && (` and volume=${query.volume}`) || ''}
  ${query.serch && ` and word like '%${query.serch}%'` || ''}`;
  st.invoke('sql', { table: 'phrase', where, ...query }).then(res => {
    query.total = res.total;
    info.list = res.list.map(v => {
      return {
        ...v,
        remark: JSON.parse(v.remark)
      }
    }) || []
    console.log(info.list);
  })
}


initData()

// st.sql({ sql: 'select word from phrase' }).then(res => {
//   console.log(words.filter(v => !res.some(s => s.word == v)));

// })

// info.phrase = setInterval(() => {
//   let item = words[info.index];
//   if (item) {
//     info.index++;
//   }
//   st.invoke('dict', { word: item }).then(res => {
//     if (res) {
//       let jsonData = JSON.stringify({
//         demo: res.web_trans && res.web_trans['web-translation']?.map(v => {
//           return { title: v.key, desc: v.trans?.map(v => v.value).toString() }
//         }) || [], j: res.blng_sents_part && res.blng_sents_part['sentence-pair']?.map(v => {
//           return { title: v.sentence, desc: v['sentence-translation'] }
//         }) || []
//       });
//       let sql = `insert into phrase (word,exp,remark) values (?,?,?) on duplicate key update word=values(word)`;
//       st.sql({ sql, value: [`${item}`, '', jsonData] }).then(res => {
//         console.log('success', item);
//       })
//     }
//   })
// }, 500)


// info.phrase = setInterval(() => {
//   let item = noword[info.index];
//   if (item) {
//     info.index++;

//     st.invoke('dict', { word: item }).then(res => {
//       if (res) {
//         let jsonData = {
//           demo: res.web_trans && res.web_trans['web-translation']?.map(v => {
//             return { title: v.key, desc: v.trans?.map(v => v.value).toString() }
//           }) || [], j: res.blng_sents_part && res.blng_sents_part['sentence-pair']?.map(v => {
//             return { title: v.sentence, desc: v['sentence-translation'] }
//           }) || []
//         }
//         let sql = `insert into phrase (word,exp,remark) values (?,?,?)`
//         st.sql({ sql, value: [`${item}`, `${jsonData.demo.length && jsonData.demo[0].desc || ''}`, JSON.stringify(jsonData)] }).then(res => {
//           console.log('success', item);
//         })
//       } else {
//         console.log('error', item)
//       }

//     })
//   } else {
//     clearInterval(info.phrase);
//     info.phrase = null;
//   }
// }, 500)


</script>

<style scoped lang='less'>
.b-0 {
  border: 0 !important;
}
</style>